package com.wengen.mybatis.reflection;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Auther: 朱稳根
 * @Date: 2018/8/28 00:02
 * @Description:
 */
public class ReflectionUtil {


    public static void setProToBeanFromResultSet(Object entity, ResultSet resultSet){
        Field[] declaredFields = entity.getClass().getDeclaredFields();
        for (int i =0 ;i<declaredFields.length;i++){
            try {
                if(declaredFields[i].getType().getSimpleName().equals("String")){
                    setProToBean(entity,declaredFields[i].getName(),resultSet.getString(declaredFields[i].getName()));
                }else if(declaredFields[i].getType().getSimpleName().equals("Integer")){
                    setProToBean(entity,declaredFields[i].getName(),resultSet.getInt(declaredFields[i].getName()));
                }else if(declaredFields[i].getType().getSimpleName().equals("Long")){
                    setProToBean(entity,declaredFields[i].getName(),resultSet.getLong(declaredFields[i].getName()));

                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 为指定的bean的proName属性的值设为value
     * @param bean 目标对象
     * @param propName 属性名称
     * @param value 值
     */
    public static void setProToBean(Object bean, String propName, Object value) {
        Field field = null;
        try {
            field = bean.getClass().getDeclaredField(propName);//获取对象指定的属性
            field.setAccessible(true);//把对象私有的权限放开
            field.set(bean,value);//为属性赋值
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
